var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var request = require('request');

var webapp = express();

var jiraUrl = "https://jira.lbi.co.uk/rest/api/2/";

// all environments
webapp.set('port', process.env.PORT || 8090);
webapp.set('views', __dirname + '/views');
webapp.engine('html', require('ejs').renderFile);

webapp.use(express.favicon());
webapp.use(express.logger('dev'));
webapp.use(express.bodyParser());
webapp.use(express.methodOverride());
webapp.use(webapp.router);
webapp.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == webapp.get('env')) {
    webapp.use(express.errorHandler());
}

webapp.get('/', function (req, res) {
    res.render('viewer.html');
});

webapp.get('/client', function (req, res) {
    res.render('client.html');
});

var webserver = http.createServer(webapp);

webserver.listen(webapp.get('port'), function () {
    console.log('Express server listening on port ' + webapp.get('port'));
});

var io = require('socket.io').listen(webserver);
var socket = io.sockets;


var StoryPointer = StoryPointer || {};

StoryPointer.Jira = {};
StoryPointer.Stories = {};

StoryPointer.Main = (function(){

    var update = function(data){
        if(isDataValid(data)){
            sendScore(data);
            updateModel(data);
        }
    };

    var sendScore = function(data) {
        socket.emit('sendScore', data);
    };

    var sendAll = function() {
        socket.emit('sendAll', StoryPointer.Stories);
    };

    var saveJira = function(data) {
        if(isJiraValid(data)){
            StoryPointer.Jira = data;
        }
    }

    var sendJira = function() {
        if(isJiraValid(StoryPointer.Jira)) {
            socket.emit('sendJira', StoryPointer.Jira);
        }
    };

    var updateModel = function(data) {
        var stories = StoryPointer.Stories;
        var jira = data.jira;

        if(stories[jira] == undefined){
            stories[jira] = {};
        }

        stories[jira][data.name] = data.score;
    };

    var isJiraValid = function(data){
        if(isNotEmpty(data.jira)){
            return true;
        }

        return false;
    };

    var isDataValid = function(data) {
        if(isNotEmpty(data.jira)){
            if(isNotEmpty(data.name)){
                if(isNotEmpty(data.score) && isNumber(data.score)) {
                    return true;
                }
            }
        }

        return false;
    };

    var isEmpty = function(str) {
        return (!str || 0 === str.length);
    };

    var isNotEmpty = function(str) {
        return !isEmpty(str);
    };

    var isNumber = function(n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
    };

    return {
        update : update,
        sendAll : sendAll,
        saveJira : saveJira,
        sendJira : sendJira
    }
})();

socket.on('connection', function (socket) {

    socket.on("sendScore", function(data) {
        StoryPointer.Main.update(data);
    });
    socket.on("sendAll", function(data) {
        StoryPointer.Main.sendAll();
    });
    socket.on("sendJira", function(data) {
        StoryPointer.Main.saveJira(data)
        StoryPointer.Main.sendJira();
    });

    socket.on("loginUser", function(data){

        request({
                    method:'GET',
                    url:jiraUrl + "user?username="+data.username,
                    headers:{"Authorization": "Basic " + data.authtoken,
                    json:true}

                },  function (error, response, body) {

            if (!error && response.statusCode == 200) {
                socket.emit("authenticated", body)
            }
        })

        console.log("LOGGING IN");
    });

    StoryPointer.Main.sendJira();
    StoryPointer.Main.sendAll();
});

